<template>
  <el-row v-loading="loading">
    <el-row v-if="editPanel.optType === 'new' && editPanel.panelInfo.nodeType === 'panel'">
      <el-col :span="18" style="height: 40px">
        <el-radio v-model="inputType" label="new"> {{ $t('panel.custom') }} </el-radio>
        <el-radio v-model="inputType" label="new_outer_template">{{ $t('panel.import_template') }} </el-radio>
        <el-radio v-model="inputType" label="new_inner_template" @click.native="getTree"
          >{{ $t('panel.copy_template') }}
        </el-radio>
      </el-col>
      <el-col v-if="inputType === 'new_outer_template'" :span="6">
        <el-button class="el-icon-upload" size="small" type="primary" @click="goFile"
          >{{ $t('panel.upload_template') }}
        </el-button>
        <input id="input" ref="files" type="file" accept=".DET" hidden @change="handleFileChange" />
      </el-col>
    </el-row>
    <el-row style="margin-top: 5px">
      <el-col :span="4">{{ editPanel.titleSuf }}{{ $t('commons.name') }}</el-col>
      <el-col :span="20">
        <el-input v-model="editPanel.panelInfo.name" clearable size="mini" />
      </el-col>
    </el-row>
    <el-row style="margin-top: 16px">
      <el-col :span="4">仪表盘图标</el-col>
      <el-col :span="20">
        <el-upload :show-file-list="false" class="avatar-uploader" :before-upload="beforeAvatarUpload">
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-col>
    </el-row>
    <el-row v-if="inputType === 'new_inner_template'" class="preview">
      <el-col :span="8" style="height: 100%; overflow-y: auto">
        <template-all-list :template-list="templateList" @showCurrentTemplateInfo="showCurrentTemplateInfo" />
      </el-col>
      <el-col :span="16" :style="classBackground" class="preview-show" />
    </el-row>
    <el-row v-if="inputType === 'new_outer_template'" class="preview" :style="classBackground" />
    <el-row class="root-class">
      <el-button size="mini" @click="cancel()">{{ $t('commons.cancel') }} </el-button>
      <el-button type="primary" size="mini" :disabled="!saveStatus" @click="save()"
        >{{ $t('commons.confirm') }}
      </el-button>
    </el-row>
  </el-row>
</template>

<script>
import { panelSave, panelUpdate } from '@/api/panel/panel'
import { showTemplateList } from '@/api/system/template'
import TemplateAllList from './template-all-list'
import { deepCopy, imgUrlTrans } from '@/components/canvas/utils/utils'
import { uploadFileResult } from '@/api/staticResource/staticResource'
const baseUrl = process.env
export default {
  components: { TemplateAllList },
  props: {
    editPanelOut: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      loading: false,
      inputType: 'new',
      fieldName: 'name',
      tableRadio: null,
      keyWordSearch: '',
      columnLabel: this.$t('panel.belong_to_category'),
      templateList: [],
      importTemplateInfo: {
        snapshot: '',
      },
      editPanel: null,
      templateSelected: false,
      imageUrl: '',
    }
  },
  computed: {
    saveStatus() {
      return this.editPanel.panelInfo.name && (this.inputType === 'new' || this.templateSelected)
    },
    classBackground() {
      if (this.importTemplateInfo.snapshot) {
        return {
          background: `url(${imgUrlTrans(this.importTemplateInfo.snapshot)}) no-repeat`,
        }
      } else {
        return {}
      }
    },
    imgUrl() {
      return imgUrlTrans(this.imageUrl)
    },
  },
  watch: {
    inputType(newVal) {
      if (newVal === 'new') {
        this.editPanel = deepCopy(this.editPanelOut)
      } else {
        this.templateSelected = false
        this.editPanel.panelInfo.name = null
        this.editPanel.panelInfo.panelStyle = null
        this.editPanel.panelInfo.panelData = null
        this.importTemplateInfo.snapshot = null
        this.editPanel.panelInfo.templateId = null
      }
    },
  },
  created() {
    this.editPanel = deepCopy(this.editPanelOut)
    if (this.editPanel?.panelInfo?.extend1) {
      let extend1 = JSON.parse(this.editPanel.panelInfo.extend1)
      this.imageUrl = extend1?.url || ''
    }
    // this.getTree()
  },
  mounted() {
    this.bindKey()
  },
  destroyed() {
    this.unBindKey()
  },
  methods: {
    entryKey(event) {
      const keyCode = event.keyCode
      if (keyCode === 13) {
        this.save()
      }
    },
    bindKey() {
      document.addEventListener('keypress', this.entryKey)
    },
    unBindKey() {
      document.removeEventListener('keypress', this.entryKey)
    },
    showCurrentTemplateInfo(data) {
      this.editPanel.panelInfo.templateId = data.id
      if (data.nodeType === 'folder') {
        this.editPanel.panelInfo.name = null
        this.importTemplateInfo.snapshot = null
        this.templateSelected = false
      } else {
        this.editPanel.panelInfo.name = data.name
        this.importTemplateInfo.snapshot = data.snapshot
        this.templateSelected = true
      }
    },
    getTree() {
      const request = {
        level: '-1',
        withChildren: true,
      }
      this.loading = true
      showTemplateList(request).then((res) => {
        this.templateList = res.data
        this.loading = false
      })
    },
    handleExceed(file) {},
    cancel() {
      this.$emit('closeEditPanelDialog')
    },
    save() {
      if (!this.editPanel.panelInfo.name) {
        this.$warning(this.$t('chart.name_can_not_empty'))
        return false
      }

      if (this.editPanel.panelInfo.name.length > 50) {
        this.$warning(this.$t('commons.char_can_not_more_50'))
        return false
      }

      if (
        !this.editPanel.panelInfo.templateId &&
        this.editPanel.optType === 'new' &&
        this.inputType === 'new_inner_template'
      ) {
        this.$warning(this.$t('chart.template_can_not_empty'))
        return false
      }
      this.editPanel.panelInfo['newFrom'] = this.inputType
      this.loading = true
      let extend1 = JSON.stringify({ url: this.imageUrl })
      if (this.editPanel.optType === 'new' || this.editPanel.optType === 'newFirstFolder') {
        panelSave({ ...this.editPanel.panelInfo, extend1 })
          .then((response) => {
            this.$message({
              message: this.$t('commons.save_success'),
              type: 'success',
              showClose: true,
            })
            this.loading = false
            this.$emit('closeEditPanelDialog', response.data)
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        panelUpdate({ ...this.editPanel.panelInfo, extend1 })
          .then((response) => {
            this.$message({
              message: this.$t('commons.save_success'),
              type: 'success',
              showClose: true,
            })
            this.loading = false
            this.$emit('closeEditPanelDialog', response.data)
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    handleFileChange(e) {
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.onload = (res) => {
        this.templateSelected = true
        const result = res.target.result
        this.importTemplateInfo = JSON.parse(result)
        this.editPanel.panelInfo.name = this.importTemplateInfo.name
        this.editPanel.panelInfo.panelStyle = this.importTemplateInfo.panelStyle
        this.editPanel.panelInfo.panelData = this.importTemplateInfo.panelData
        this.editPanel.panelInfo.dynamicData = this.importTemplateInfo.dynamicData
        this.editPanel.panelInfo.staticResource = this.importTemplateInfo.staticResource
      }
      reader.readAsText(file)
    },
    goFile() {
      this.$refs.files.click()
    },
    handleAvatarSuccess(res) {},
    beforeAvatarUpload(file) {
      uploadFileResult(file, (fileUrl) => {
        console.log(fileUrl)
        this.imageUrl = fileUrl
      })
    },
  },
}
</script>

<style scoped>
.my_table ::v-deep .el-table__row > td {
  /* 去除表格线 */
  border: none;
  padding: 0 0;
}

.my_table ::v-deep .el-table th.is-leaf {
  /* 去除上边框 */
  border: none;
}

.my_table ::v-deep .el-table::before {
  /* 去除下边框 */
  height: 0;
}

.root-class {
  margin: 15px 0px 5px;
  text-align: right;
  border-top: 1px solid #eee;
  margin-left: -20px;
  margin-right: -20px;
  padding-top: 10px;
  padding-right: 20px;
  margin-bottom: -20px;
}

.preview {
  margin-top: 5px;
  border: 1px solid #e6e6e6;
  height: 250px !important;
  overflow: hidden;
  background-size: 100% 100% !important;
}

.preview-show {
  border-left: 1px solid #e6e6e6;
  height: 250px;
  background-size: 100% 100% !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  border: 1px dashed #e6e6e6;
}

.avatar {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 5px;
}
</style>
